import { onBeforeUnmount, onMounted, reactive } from 'vue';
import { useHttp } from './useHttp';

export function useTime() {
  const { get } = useHttp();
  const state = reactive({
    timerId: 0 as any,
    remoteTimer: '',
    timer: '',
  });

  function getRemoteTime(callback: () => any) {
    return get('/time')
      .then((result) => {
        if (result.status && result.status === 200) {
          state.remoteTimer = result.data || '';
          callback();
        }
      })
      .catch((err) => {
        console.error(err);
      });
  }

  function getTime(timeStr: string) {
    let date = new Date(+timeStr),
      month = date.getMonth() + 1,
      minutes = date.getMinutes(),
      seconds = date.getSeconds(),
      time = `${date.getHours()}:${minutes < 10 ? '0' + minutes : minutes}:${
        seconds < 10 ? '0' + seconds : seconds
      }`;
    return `${date.getFullYear()}.${
      month < 10 ? '0' + month : month
    }.${date.getDate()} ${time}`;
  }

  function start() {
    state.remoteTimer = (+state.remoteTimer + 1000).toString();
    state.timer = getTime(state.remoteTimer || String(Date.now()));
  }

  onMounted(() => {
    getRemoteTime(() => {
      state.timerId = setInterval(() => {
        start();
      }, 1000);
    });
  });

  onBeforeUnmount(() => {
    clearInterval(state.timerId);
    state.timerId = 0;
  });

  return {
    timerState: state,
  };
}
